package cn.iocoder.an.module.mold.service.drawingno;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.an.module.business.service.equipmentmanage.EquipmentManageService;
import cn.iocoder.an.module.mold.service.category.CategoryService;
import cn.iocoder.an.module.mold.service.recheckcategory.RecheckCategoryService;
import cn.iocoder.an.module.mold.service.storage.StorageService;
import cn.iocoder.an.module.mold.service.upkeepcategory.UpkeepCategoryService;
import cn.iocoder.an.module.mold.service.warehouse.WarehouseService;
import cn.iocoder.an.module.mold.utils.ImportRespVO;
import io.micrometer.common.util.StringUtils;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import cn.iocoder.an.module.mold.controller.admin.drawingno.vo.*;
import cn.iocoder.an.module.mold.dal.dataobject.drawingno.DrawingNoDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.util.object.BeanUtils;
import cn.iocoder.an.module.mold.dal.mysql.drawingno.DrawingNoMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.an.module.mold.enums.ErrorCodeConstants.*;

/**
 * 模具图号 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class DrawingNoServiceImpl implements DrawingNoService {

    @Resource
    private DrawingNoMapper drawingNoMapper;

    @Resource
    private CategoryService categoryService;

    @Resource
    private UpkeepCategoryService upkeepCategoryService;

    @Resource
    private RecheckCategoryService recheckCategoryService;

    @Resource
    private EquipmentManageService equipmentManageService;


    @Resource
    private WarehouseService warehouseService;

    @Resource
    private StorageService storageService;

    @Override
    public Long createDrawingNo(DrawingNoSaveReqVO createReqVO) {
        // 插入
        DrawingNoDO drawingNo = BeanUtils.toBean(createReqVO, DrawingNoDO.class);
        drawingNoMapper.insert(drawingNo);

        // 返回
        return drawingNo.getId();
    }

    @Override
    public void updateDrawingNo(DrawingNoSaveReqVO updateReqVO) {
        // 校验存在
        validateDrawingNoExists(updateReqVO.getId());
        // 更新
        DrawingNoDO updateObj = BeanUtils.toBean(updateReqVO, DrawingNoDO.class);
        drawingNoMapper.updateById(updateObj);
    }

    @Override
    public void deleteDrawingNo(Long id) {
        // 校验存在
        validateDrawingNoExists(id);
        // 删除
        drawingNoMapper.deleteById(id);
    }

    @Override
    public void deleteDrawingNoListByIds(List<Long> ids) {
        // 删除
        drawingNoMapper.deleteByIds(ids);
    }


    private void validateDrawingNoExists(Long id) {
        if (drawingNoMapper.selectById(id) == null) {
            throw exception(DRAWING_NO_NOT_EXISTS);
        }
    }

    @Override
    public DrawingNoDO getDrawingNo(Long id) {
        return drawingNoMapper.selectById(id);
    }

    @Override
    public PageResult<DrawingNoDO> getDrawingNoPage(DrawingNoPageReqVO pageReqVO) {
        return drawingNoMapper.selectPage(pageReqVO);
    }


    @Override
    public List<DrawingNoDO> getDrawingNoAll() {
        return drawingNoMapper.selectList();
    }

    ;


    /**
     * 模糊搜索模具图号，返回IDS
     *
     * @return 图号Ids
     */
    @Override
    public List<Long> getIdsByDrawingNo(String drawingNo) {
        List<DrawingNoDO> drawingNoList = drawingNoMapper.selectListByDrawingNoLike(drawingNo);
        // 提取对象中的 id 字段，转换为 List<Long>
        return convertList(drawingNoList, DrawingNoDO::getId);
    }

    /**
     * 根据图号获取图号对象
     *
     * @return DrawingNoDO 对象
     */
    @Override
    public DrawingNoDO  getObByDrawingNo(String drawingNo) {
        DrawingNoDO drawingNoDo = drawingNoMapper.selectFirstOne(DrawingNoDO::getDrawingNo, drawingNo);
        return  drawingNoDo;
    }


    @Override
    public ImportRespVO importDrawingNoList(List<DrawingNoImportExcelVO> iomportDrawingNo, boolean isUpdateSupport) {
        if (CollUtil.isEmpty(iomportDrawingNo)) {
            throw exception(DRAWING_IMPORT_NOT_EXISTS);
        }
        ImportRespVO respVO = ImportRespVO.builder().insertNameList(new ArrayList<>())
                .updateNameList(new ArrayList<>()).failureMap(new LinkedHashMap<>()).build();

        AtomicInteger count = new AtomicInteger(1);
        iomportDrawingNo.forEach(item -> {
            count.incrementAndGet();//记录行号
            // 2.1.1 校验图号
            if (StringUtils.isEmpty(item.getDrawingNo())) {
                return;
            }
            // 2.1.2 校验客户名
            if (StringUtils.isEmpty(item.getCustomer())) {
                respVO.getFailureMap().put(item.getDrawingNo(), "客户名不能为空!");
                return;
            }
            // 2.1.3 模具类型编码
            if (StringUtils.isEmpty(item.getCategoryCode())) {
                respVO.getFailureMap().put(item.getDrawingNo(), "模具类型编码不能为空!");
                return;
            } else {
                try {
                    Long deptId = categoryService.getCategoryIdByCode(item.getCategoryCode());
                    item.setCategoryId(deptId);
                } catch (Exception e) {
                    respVO.getFailureMap().put(item.getDrawingNo(), e.getMessage());
                    return;
                }
            }

            // 2.1.4 保养类型
            if (StringUtils.isEmpty(item.getUpkeepCode())) {
                respVO.getFailureMap().put(item.getDrawingNo(), "保养类型不能为空!");
                return;
            } else {
                try {
                    Long upkeepId = upkeepCategoryService.getUpkeepCategoryIdByCode(item.getUpkeepCode());
                    item.setUpkeepId(upkeepId);
                } catch (Exception e) {
                    respVO.getFailureMap().put(item.getDrawingNo(), e.getMessage());
                    return;
                }
            }

            // 2.1.5 复检类型
            if (StringUtils.isEmpty(item.getRecheckCode())) {
                respVO.getFailureMap().put(item.getDrawingNo(), "复检类型不能为空!");
                return;
            } else {
                try {
                    Long recheckId = recheckCategoryService.getRecheckCategoryIdByCode(item.getRecheckCode());
                    item.setRecheckId(recheckId);
                } catch (Exception e) {
                    respVO.getFailureMap().put(item.getDrawingNo(), e.getMessage());
                    return;
                }
            }
            // 2.1.6 寿命扣减方式

            // 2.1.7 默认库存状态

            // 2.1.8 默认绑定设备编码
            if (StringUtils.isEmpty(item.getDevCode())) {
                respVO.getFailureMap().put(item.getDrawingNo(), "设备编码不能为空!");
                return;
            } else {
                try {
                    Long equipmentId = equipmentManageService.getEquipmentIdByCode(item.getDevCode());
                    item.setDevId(equipmentId);
                } catch (Exception e) {
                    respVO.getFailureMap().put(item.getDrawingNo(), e.getMessage());
                    return;
                }
            }

            // 2.1.9 默认仓库
            if (StringUtils.isEmpty(item.getWarehouseCode())) {
                respVO.getFailureMap().put(item.getDrawingNo(), "仓库不能为空!");
                return;
            } else {
                try {
                    Long houseId = warehouseService.getWarehouseIdByCode(item.getWarehouseCode());
                    item.setWarehouseId(houseId);
                } catch (Exception e) {
                    respVO.getFailureMap().put(item.getDrawingNo(), e.getMessage());
                    return;
                }
            }

            // 2.1.10 默认储位
            if (StringUtils.isEmpty(item.getStorageCode())) {
                respVO.getFailureMap().put(item.getDrawingNo(), "储位不能为空!");
                return;
            } else {
                try {
                    Long storageId = storageService.getStorageId(item.getWarehouseId(), item.getStorageCode());
                    item.setStorageId(storageId);
                } catch (Exception e) {
                    respVO.getFailureMap().put(item.getDrawingNo(), e.getMessage());
                    return;
                }
            }

            //更新或者插入
            //判断图号是否重复
            String drawingNO = item.getDrawingNo();
            DrawingNoDO exists = drawingNoMapper.selectFirstOne(
                    DrawingNoDO::getDrawingNo, drawingNO
            );

            if (exists != null) {
                //如果存在 判断是否允许更新
                if (isUpdateSupport) {
                    //允许更新
                    //设置ID
                    item.setId(exists.getId());
                    DrawingNoDO updateDrawingNo = BeanUtils.toBean(item, DrawingNoDO.class);
                    drawingNoMapper.updateById(updateDrawingNo);
                    respVO.getUpdateNameList().add(item.getDrawingNo());
                } else {
                    respVO.getFailureMap().put(item.getDrawingNo(), DRAWING_REPEATS.getMsg());
                }
            } else {
                drawingNoMapper.insert(BeanUtils.toBean(item, DrawingNoDO.class));
                respVO.getInsertNameList().add(item.getDrawingNo());
            }
        });
        return respVO;

    }

}